import cv2
import numpy as np
import datetime
#加载视频
cap = cv2.VideoCapture("E:\opencv\opencv\sources\samples\data\\vtest.avi")
#构建焦点检测所需函数
feature_params = dict(maxCorners=100,qualityLevel=0.3,minDistance=7)
#构建LK所需参数
lk_params = dict(winSize=(15,15),maxLevel=2)
#构建随机颜色
color = np.random.randint(0,255,(100,3))
#获取第一帧图像
ret,first_frame = cap.read()
#转化灰度图像
grayFrame = cv2.cvtColor(first_frame,cv2.COLOR_BGR2GRAY)
#获取检测特征点
p0 = cv2.goodFeaturesToTrack(grayFrame,mask=None,**feature_params)
#创建一个mask，用于进行横线的绘制
mask = np.zeros_like(first_frame)

while True:
    ret,frame = cap.read()
    #当图像读取完毕时，退出不然会报错
    if not ret:
        break
    frame_gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    #进行LK光流检测
    pl,st,err = cv2.calcOpticalFlowPyrLK(grayFrame,frame_gray,p0,None,**lk_params)
    #读取运动了的角点
    good_new = pl[st==1]
    good_old = p0[st==1]
    #绘制轨迹
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask,(a,b),(c,d),color[i].tolist(),2)
        frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
    #图片合成用于展示
    img = cv2.add(frame,mask)
    cv2.imshow("img",img)

    k = cv2.waitKey(30)&0xff
    if k == 27:
        break
    # 更新前一帧图片和角点的位置
    grayFrame = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)

cv2.destroyAllWindows()
cap.release()